//
//  ChangePasswordViewController.m
//  ZYZB
//
//  Created by ENERGY on 2018/7/11.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "ChangePasswordViewController.h"
#import "SetLoginPasswordViewController.h"
@interface ChangePasswordViewController ()
@property (nonatomic, strong)UILabel * haveSendTitleLab;
@property (nonatomic, strong)UITextField * codeTextField;//验证码
@end

@implementation ChangePasswordViewController (networking)
- (void)sendVerificationCodeData{
    [self showprogressHUD];
    NSString * timeStr = [self currentTimeStr];
    //str
    NSDictionary * dic = @{
                           @"userName":[UserModel sharedInstanced].mobile,
                           @"phone":[UserModel sharedInstanced].mobile,
                           @"t":timeStr
                           };
    //sign
    NSDictionary * signDic = @{
                               @"userName":[UserModel sharedInstanced].mobile,
                               @"phone":[UserModel sharedInstanced].mobile,
                               @"t":timeStr,
                               @"merchantNo":@"80d709a97af1b8ab"
                               };
    SortMD5Code * md5Code = [[SortMD5Code alloc] init];
    NSString * jsonStr = [md5Code getJsonWithStrDic:dic withSignDic:signDic];
    NSData *postData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:@"http://120.78.157.132:82/index.php/sendCode/index?api=api1001"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //设置请求方式
    request.HTTPMethod = @"POST";
    //设置请求参数
    request.HTTPBody = postData;
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        [self hiddenProgressHUD];
        if (connectionError) {
            if (connectionError.code == -1001) {
                [self.view makeToast:@"请求网络超时，请稍后再试" duration:1 position:CSToastPositionCenter];
            }
        }else{
            NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];//data解析为dictionary
            if (!dictionary) {
                NSLog(@"数据缺失");
                return;
            }
            NSString * compareMD5Str = [md5Code encodeStringWithDictionary:dictionary];
            NSString * signResult = [dictionary objectForKey:@"sign"];//接到的json串sign字段
            NSDictionary * jsonData = [md5Code getNSDictionaryData:dictionary];//解析为字典数据
            if ([compareMD5Str isEqualToString:signResult]) {
                NSLog(@"成功");
                NSDictionary * contentDic = jsonData[@"body"][0];
                
            }else{
                NSLog(@"失败");
            }
        }
    }];
}
@end
@implementation ChangePasswordViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    //返回按钮
    UIButton * backBtn = [[UIButton alloc] initWithFrame:CGRectMake(18/WIDTH_6_SCALE, 14/WIDTH_6_SCALE + 24 + 20, 24/WIDTH_6_SCALE, 30/WIDTH_6_SCALE)];
    [backBtn addTarget:self action:@selector(backBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setImage:[UIImage imageNamed:@"out"] forState:UIControlStateNormal];
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"修改登录密码";
    
    [self setUpViews];//搭建页面
    [self sendVerificationCodeData];//网络接口
}

- (void)setUpViews{
    __weak typeof (self)weakSelf = self;
    //手机号
    self.haveSendTitleLab = [[UILabel alloc] init];
    [self.view addSubview:self.haveSendTitleLab];
    NSString * phoneStr = [NSString stringWithFormat:@"已发送验证码到  %@  手机上，请输入验证码后更改", [UserModel sharedInstanced].mobile];
    [self label:self.haveSendTitleLab withFont:DEF_FontSize_12 withText:phoneStr withTextColor:[UIColor blackColor] withTextAlignment:NSTextAlignmentLeft withView:self.view];
    self.haveSendTitleLab.numberOfLines = 0;
    self.haveSendTitleLab.lineBreakMode = 0;
    [self.haveSendTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view.mas_left).mas_offset(25/WIDTH_6_SCALE);
        make.right.equalTo(weakSelf.view.mas_right).mas_offset(-25/WIDTH_6_SCALE);
        make.top.equalTo(weakSelf.view.mas_top).mas_offset(20/WIDTH_6_SCALE);
    }];
    //验证码
//    self.codeTextField = [[UITextField alloc]initWithFrame:CGRectMake(24, 100+64, SCREEN_WIDTH - 48, 80)];
    self.codeTextField = [[UITextField alloc]init];
    [self.view addSubview:self.codeTextField];
    //设置光标起始位置
    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,10,self.codeTextField.height )];
    self.codeTextField.leftView = leftView;
    self.codeTextField.leftViewMode = UITextFieldViewModeAlways;
    CGRect frame = [@"请输入验证码" boundingRectWithSize:CGSizeMake(MAXFLOAT, self.codeTextField.height) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil];
    //设置textFiled的段落格式
    NSMutableParagraphStyle *style = [self.codeTextField.defaultTextAttributes[NSParagraphStyleAttributeName] mutableCopy];
    //设置垂直对齐
    style.minimumLineHeight = self.codeTextField.font.lineHeight - (self.codeTextField.font.lineHeight - [UIFont systemFontOfSize:14.0].lineHeight) / 2.0;
    //水平对齐
    style.firstLineHeadIndent = (self.codeTextField.width - frame.size.width )*0.5;
    //设置placeholder的样式
    self.codeTextField.attributedPlaceholder = [[NSAttributedString alloc]initWithString:@"请输入验证码" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSParagraphStyleAttributeName:style,NSForegroundColorAttributeName:[UIColor blackColor]}];
    [self.codeTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(weakSelf.view.mas_centerX);
        make.height.mas_offset(13/WIDTH_6_SCALE);
        make.width.mas_offset(100/WIDTH_6_SCALE);
        make.top.equalTo(weakSelf.haveSendTitleLab.mas_bottom).mas_offset(45/WIDTH_6_SCALE);
    }];
    //横线
    UIView * lineView = [[UIView alloc] init];
    lineView.backgroundColor = getColor(grayColor);
    [self.view addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weakSelf.codeTextField);
        make.height.mas_offset(1/WIDTH_6_SCALE);
        make.top.equalTo(weakSelf.codeTextField.mas_bottom).mas_offset(4/WIDTH_6_SCALE);
    }];
    //确认更改
    UIButton * sureChangeBtn = [[UIButton alloc] init];
    [self.view addSubview:sureChangeBtn];
    [self button:sureChangeBtn withBGColor:getColor(@"3675bd") withLayerBorderColor:nil withLayerBorderWith:0 withCornerRadius:6 withMasksToBounds:YES withViwe:self.view];
    [sureChangeBtn setTitle:@"确认更改" forState:UIControlStateNormal];
    [sureChangeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    sureChangeBtn.titleLabel.font = DEF_FontSize_12;
    [sureChangeBtn addTarget:self action:@selector(sureChangeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [sureChangeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view.mas_left).mas_offset(58/WIDTH_6_SCALE);
        make.right.equalTo(weakSelf.view.mas_right).mas_offset(-58/WIDTH_6_SCALE);
        make.height.mas_offset(38/WIDTH_6_SCALE);
        make.top.equalTo(lineView.mas_bottom).mas_offset(56/WIDTH_6_SCALE);
    }];
}
#pragma mark - action
- (void)backBtnClick:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)sureChangeBtnClick:(UIButton *)sender{
    if ([self.codeTextField.text isEqualToString:@""] || self.codeTextField.text == nil || self.codeTextField.text.length == 0) {
        [self.view makeToast:@"请输入验证码" duration:2 position:CSToastPositionCenter];
    }else{
        SetLoginPasswordViewController * setLoginPasswordVC = [[SetLoginPasswordViewController alloc] init];
        setLoginPasswordVC.verificationCodeStr = self.codeTextField.text;
        [self.navigationController pushViewController:setLoginPasswordVC animated:YES];
    }
}
@end
